# -*-coding:utf-8-*-
import requests
import getcity
import xlrd
import xlwt

def transform(geo):
    params={
        "address":geo,"key":"b9148eb275960bbc3116483e2eb01a70"
    }
    url="https://restapi.amap.com/v3/geocode/geo"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'
    }
    response = requests.get(url=url, headers=headers, params=params)
    text=response.text
    str=text.find("location")
    if str == -1:
        return -1
    str=str+11
    end=text.find("\",",str)
    return text[str:end]

if __name__ == "__main__":
    getcity.getCity()
    data=xlrd.open_workbook("./city.xls")
    table=data.sheet_by_index(0)
    nrows=table.nrows

    workbook = xlwt.Workbook(encoding='utf-8')
    worksheet = workbook.add_sheet('city')

    newrow=0
    for row in range(nrows):
        if row == 0:
            worksheet.write(newrow,0,table.cell(row,0).value)
            worksheet.write(newrow,1,table.cell(row,1).value)
            newrow=newrow+1
        else:
            str=transform(table.cell(row,0).value)
            if str == -1:
                continue
            worksheet.write(newrow,0,table.cell(row,0).value)
            worksheet.write(newrow,1,transform(table.cell(row,0).value))
            newrow=newrow+1
    workbook.save("newcity.xls")
    print("已对应生成location")